<template>
  <div class="row">
    <div class="col-xs-12">
      <el-form class="el-form-col" :model="model" :rules="rules" label-position="left" ref="elForm" label-width="110px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>订单信息</span>
          </div>
          <el-row>
            <el-col :lg="8" :md="12"  :xl="6">
              <el-form-item label="关联单号：">
                <span>{{chOrderService.orderNo}}</span>
              </el-form-item>
            </el-col>
            <el-col  :lg="8" :md="12" :xl="6">
              <el-form-item label="入库仓：">
                <span>{{chOrderService.warehouse}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12"  :xl="6">
              <el-form-item label="商家名称：">
                <span>{{chOrderService.cargoOwner}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12"  :xl="6">
              <el-form-item label="关联订单类型：">
                <span>{{orderType | filterDataBaseDictionary}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12"  :xl="6">
              <el-form-item label="仓储类型：">
                <span>{{chOrderService.storageTypeCode | filterDataBaseDictionary}}</span>
              </el-form-item>
            </el-col>
            <el-col  :lg="8" :md="12" :xl="6">
              <el-form-item label="录单员：">
                <span>{{chOrderService.founderUserName}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="录单时间：">
                <span>{{chOrderService.foundDate | unixTimestampFilter('YYYY-MM-DD HH:mm')}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12" :xl="6" v-if="orderType === 'STORAGEORDERTYPE01'">
              <el-form-item label="录入商品总数：">
                <span>{{chOrderService.totalProduct}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" v-if="orderType === 'STORAGEORDERTYPE01'">
          <div slot="header" class="clearfix">
            <span>客户信息</span>
          </div>
          <el-row>
            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="客户姓名：">
                <span>{{chOrderConsigneeInfo.consigneName}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="客户电话：">
                <span>{{chOrderConsigneeInfo.consignePhone}}</span>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :md="12" :xl="6">
              <el-form-item label="客户地址：">
                <span>{{chOrderConsigneeInfo.consigneProvince}}{{chOrderConsigneeInfo.consigneCity}}{{chOrderConsigneeInfo.consigneDistrict}}{{chOrderConsigneeInfo.consigneAddress}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <!-- 服务订单 -->
        <el-tabs v-model="tabState" v-if="orderType === 'STORAGEORDERTYPE01'">
        <el-tab-pane name="1" label="未确认" v-if="state == 0 || state == 1">
          <Portlet :title="productType">
            <div slot="tools">
              <span class="font-red">提示：请勾选已经收货的商品并填写收货信息</span>
              <el-button type="primary" :loading="loading" @click.prevent="submit">确认收货</el-button>
            </div>
            <el-row>
              <el-col :lg="24" :md="24">
                <el-form ref="searchForm" class="el-form-col" :model="search" inline>
                  <el-row :gutter="15">
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item prop="manufacturerName" label="厂家名称">
                        <el-input clearable placeholder="" v-model="search.manufacturerName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item prop="productName" label="商品名称">
                        <el-input clearable placeholder="" v-model="search.productName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item >
                        <el-button type="primary" @click.prevent="reset">重置</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                  {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
               ]">
                  <el-table
                    border
                    max-height="500"
                    :data="model.productDetailBeans | filterActive(this.search)"
                    show-summary
                    :summary-method="getSummaries"
                    class="text-center"
                    @selection-change="handleSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="55">
                    </el-table-column>
                    <el-table-column
                      prop="manufacturerName"
                      label="厂家名称"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="productName"
                      label="商品名称">
                    </el-table-column>
                    <el-table-column
                      prop="memo"
                      label="备注">
                    </el-table-column>
                    <el-table-column
                      v-if="state == 0"
                      prop="proudctNum"
                      label="录入商品数量">
                    </el-table-column>
                    <el-table-column
                      v-if="state == 1"
                      prop="noArriveNum"
                      label="待收货商品数量">
                    </el-table-column>
                    <el-table-column
                      prop="arriveNum"
                      width="200px"
                      label="已收货商品数量">
                      <template slot-scope="scope">
                        <el-form-item label-width="0" :prop="'productDetailBeans.' + scope.$index + '.arriveNum'" :rules="[
                        {required: true, message: '实际入库包件必须', trigger: 'change'}
                     ]">
                          <el-input-number v-model="scope.row.arriveNum" :min="0" :max="scope.row.noArriveNum || 0" label="描述文字"></el-input-number>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="arrivePackageNum"
                      width="190"
                      label="收货包件数量">
                      <template slot-scope="scope">
                        <el-form-item v-if="chOrderService.productType == 2 || chOrderService.productType == 3" label-width="0" :prop="'productDetailBeans.' + scope.$index + '.arrivePackageNum'" :rules="[
                     ]">
                          <el-input-number v-model="scope.row.arrivePackageNum" :min="0" :max="99999" label="描述文字"></el-input-number>
                        </el-form-item>
                        <span v-else>{{scope.row.arriveNum * scope.row.packageNum}}</span>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>
        </el-tab-pane>
        <el-tab-pane name="2" label="已确认" v-if="state == 1 || state == 2">
          <Portlet :title="productType">
            <el-row>
              <el-col :span="24">
                <el-form ref="searchForm" class="el-form-col" :model="search" inline>
                  <el-row :gutter="15">
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item prop="manufacturerName" label="厂家名称">
                        <el-input clearable placeholder="" v-model="search.manufacturerName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item prop="productName" label="商品名称">
                        <el-input clearable placeholder="" v-model="search.productName"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :md="12" :lg="8" :xl="6">
                      <el-form-item >
                        <el-button type="primary" @click.prevent="reset">重置</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
             ]">
                  <el-table
                    border
                    max-height="500"
                    :data="model.productDetailBeans | filterActive(this.search)"
                    class="text-center"
                    show-summary
                    :summary-method="getSummaries"
                    @selection-change="handleSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="55">
                    </el-table-column>
                    <el-table-column
                      prop="inputWarehouseNo"
                      label="入库单号"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="manufacturerName"
                      label="厂家名称"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="productName"
                      label="商品名称">
                    </el-table-column>
                    <el-table-column
                      prop="memo"
                      label="备注">
                    </el-table-column>
                    <el-table-column
                      prop="proudctNum"
                      label="商品数量">
                    </el-table-column>
                    <el-table-column
                      prop="arrivePackageNum"
                      label="包件数量">
                    </el-table-column>
                    <el-table-column
                      prop="packageName"
                      label="确认收货时间">
                      <template slot-scope="scope">
                        {{ scope.row.arriveTime | unixTimestampFilter('YYYY-MM-DD HH:mm')}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="arrivePersonName"
                      label="提交人">
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>
        </el-tab-pane>
        </el-tabs>
        <!-- 入库订单 -->
        <el-tabs v-model="tabState" v-else>
          <el-tab-pane name="1" label="未确认" v-if="state == 0 || state == 1">
            <Portlet :title="productType">
              <div slot="tools">
                <span class="font-red">提示：请勾选已经收货的商品并填写收货信息</span>
                <el-button type="primary" :loading="loading" @click.prevent="submit">确认收货</el-button>
              </div>
              <el-row>
                <el-col :lg="24" :md="24">
                  <el-form ref="searchForm" class="el-form-col" :model="search" inline>
                    <el-row :gutter="15">
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item prop="manufacturerName" label="厂家名称">
                          <el-input clearable placeholder="" v-model="search.manufacturerName"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item prop="productName" label="商品名称">
                          <el-input clearable placeholder="" v-model="search.productName"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item >
                          <el-button type="primary" @click.prevent="reset">重置</el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                    {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
                 ]">
                    <el-table
                      border
                      max-height="500"
                      :data="model.productDetailBeans | filterActive(this.search)"
                      show-summary
                      :summary-method="getSummaries"
                      class="text-center"
                      @selection-change="handleSelectionChange"
                    >
                      <el-table-column
                        type="selection"
                        width="55">
                      </el-table-column>
                      <el-table-column
                        prop="manufacturerName"
                        label="厂家名称"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="productNo"
                        label="商品编号"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="productName"
                        label="商品名称">
                      </el-table-column>
                      <el-table-column
                        prop="packageCode"
                        label="包件编号">
                      </el-table-column>
                      <el-table-column
                        prop="productName"
                        label="包件名称">
                      </el-table-column>
                      <el-table-column
                        v-if="state == 0"
                        prop="packageNums"
                        label="录入包件数">
                      </el-table-column>
                      <el-table-column
                        v-if="state == 1"
                        prop="noArriveNum"
                        label="待确认包件数">
                      </el-table-column>
                      <el-table-column
                        prop="arrivePackageNum"
                        width="190"
                        label="收货包件数量">
                        <template slot-scope="scope">
                          <el-form-item label-width="0" :prop="'productDetailBeans.' + scope.$index + '.arrivePackageNum'" :rules="[
                       ]">
                            <el-input-number v-model="scope.row.arriveNum" :min="0" :max="99999" label="描述文字"></el-input-number>
                          </el-form-item>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>
              </el-row>
            </Portlet>
          </el-tab-pane>
          <el-tab-pane name="2" label="已确认" v-if="state == 1 || state == 2">
            <Portlet :title="productType">
              <el-row>
                <el-col :span="24">
                  <el-form ref="searchForm" class="el-form-col" :model="search" inline>
                    <el-row :gutter="15">
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item prop="manufacturerName" label="厂家名称">
                          <el-input clearable placeholder="" v-model="search.manufacturerName"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item prop="productName" label="商品名称">
                          <el-input clearable placeholder="" v-model="search.productName"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :md="12" :lg="8" :xl="6">
                        <el-form-item >
                          <el-button type="primary" @click.prevent="reset">重置</el-button>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="0" prop="productDetailBeans" :rules="[
                  {required: true, message: '货物信息必须', trigger: 'change', type: 'array'}
               ]">
                    <el-table
                      border
                      max-height="500"
                      :data="model.productDetailBeans | filterActive(this.search)"
                      class="text-center"
                      show-summary
                      :summary-method="getSummaries"
                      @selection-change="handleSelectionChange"
                    >
                      <el-table-column
                        type="selection"
                        width="55">
                      </el-table-column>
                      <el-table-column
                        prop="inputWarehouseNo"
                        label="入库单号"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="manufacturerName"
                        label="厂家名称"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="productNo"
                        label="商品编号"
                      >
                      </el-table-column>
                      <el-table-column
                        prop="productName"
                        label="商品名称">
                      </el-table-column>
                      <el-table-column
                        prop="packageCode"
                        label="包件编号">
                      </el-table-column>
                      <el-table-column
                        prop="packageName"
                        label="包件名称">
                      </el-table-column>
                      <el-table-column
                        prop="packageNums"
                        label="包件数量">
                      </el-table-column>
                      <el-table-column
                        prop="packageName"
                        label="确认收货时间">
                        <template slot-scope="scope">
                          {{ scope.row.arriveTime | unixTimestampFilter}}
                        </template>
                      </el-table-column>
                      <el-table-column
                        prop="arrivePersonName"
                        label="提交人">
                      </el-table-column>
                    </el-table>
                  </el-form-item>
                </el-col>
              </el-row>
            </Portlet>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
  </div>
</template>
<script>
import Truncate from '@/components/Truncate'
import DBLike from '@/utils/DBLike'
import {dotData, alert} from '@/utils'
import {decimalNumFilter, unixTimestampFilter, filterDataBaseDictionary} from '@/filters'

export default {
  name: 'arriveManagerArrive',
  components: {
    Truncate
  },
  filters: {
    filterDataBaseDictionary,
    decimalNumFilter,
    unixTimestampFilter,
    filterActive: (arr, search) => {
      return new DBLike(arr).search(search)
    }
  },
  data() {
    return {
      id: this.$route.params.id,
      state: this.$route.query.state,
      orderType: this.$route.query.orderType,
      tabState: '',
      loading: false,
      search: {
        manufacturerName: '',
        productName: '',
        packageName: ''
      },
      params: {
        id: this.$route.params.orderId
      },
      packageIdArr: [],
      picker: {},
      chOrderService: {},
      chOrderConsigneeInfo: {},
      isVisible: false,
      model: {
        productDetailBeans: [],
        warehouseId: '',
        cargoOwnerId: ''
      },
      rules: {},
      multipleSelection: [],
      arriveState: 1, // 1 部分收货  2 全部收货
      totalArrive: 0,
      totalArrivePackage: 0,
      totalNoArrive: 0
    }
  },
  created() {
    if (this.id) {
      this.getDetail()
    }
    if (this.state === '2' || this.state === 2) {
      this.tabState = '2'
    } else {
      this.tabState = '1'
    }
  },
  computed: {
    productType() {
      let productTypeValue = dotData(this.chOrderService, 'productType') || ''
      if (productTypeValue === 1) {
        return '商品信息  商品类型：标准商品'
      } else if (productTypeValue === 2) {
        return '商品信息  商品类型：通用商品'
      } else if (productTypeValue === 3) {
        return '商品信息  商品类型：自定义商品'
      } else { // 默认
        return '商品信息  商品类型：标准商品'
      }
    }
  },
  watch: {
    'tabState'(val, oldVal) {
      if (val && this.orderType) {
        this.getDatasTable()
      }
    }
  },
  methods: {
    searchFunc() {
      console.log('searchFunc')
    },
    // reset 重置搜索框
    reset(searchForm) {
      this.$refs.searchForm.resetFields()
    },
    // 获取详情
    getDetail() {
      this.$ajax.get('/ms-terminal-order/ch-arrive/get-order-detail', {orderId: this.id}).then(response => {
        if (!response.data) {
          return
        }
        this.chOrderService = response.data || {}
        this.chOrderConsigneeInfo = dotData(response.data, 'chOrderConsigneeInfo') || {}
        this.orderType = response.data.orderType
        this.getDatasTable()
      })
    },
    // 获取包件列表
    getDatasTable() {
      this.$ajax.get('/ms-warehouse-order/ch-arrive/get-product-detail', {
        orderId: this.id,
        tabState: this.tabState,
        orderType: this.orderType
      }).then(response => {
        this.model.productDetailBeans = response.data
        this.totalNoArrive = 0
        if (Array.isArray(this.model.productDetailBeans)) {
          this.model.productDetailBeans.forEach(item => {
            item.arrivePackageNum = item.packageNums
            this.totalNoArrive += item.noArriveNum
            // 默认填写
            item.arriveNum = item.noArriveNum
          })
        }
      })
    },
    // 列表选择
    handleSelectionChange(val) {
      this.multipleSelection = []
      this.multipleSelection = val
    },
    getSummaries(param) {
      const {columns, data} = param
      const sums = []
      columns.forEach((column, index) => {
        const values = data.map(item => Number(item[column.property]))
        if (index === 0) {
          sums[index] = '合计'
        } else {
          if (column.property === 'noArriveNum' || column.property === 'arriveNum' || column.property === 'arrivePackageNum' || column.property === 'proudctNum' || column.property === 'packageNums') {
            let temp = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            // sums[index] = decimalNumFilter(temp)
            if (column.property === 'arrivePackageNum') {
              if (this.chOrderService.productType === 2 || this.chOrderService.productType === 3) {
                sums[index] = data.reduce((total, v) => {
                  return total + v.arrivePackageNum
                }, 0)
              } else {
                if (this.orderType === 'STORAGEORDERTYPE01' && this.tabState === '1') {
                  sums[index] = data.reduce((total, v) => {
                    return total + v.packageNum * v.arriveNum
                  }, 0)
                } else {
                  sums[index] = data.reduce((total, v) => {
                    return total + v.arrivePackageNum
                  }, 0)
                }
              }
            } else {
              sums[index] = decimalNumFilter(temp, (column.property === 'noArriveNum' || column.property === 'arriveNum' || column.property === 'proudctNum' || column.property === 'packageNums') ? 0 : 2)
            }
          } else {
            sums[index] = ''
          }
        }
      })
      return sums
    },
    submit() {
      this.$refs.elForm.validate(result => {
        this.loading = true
        this.loading = false
        let productDetailBeans = []
        if (Array.isArray(this.multipleSelection)) {
          let arr = this.multipleSelection
          if (arr.length <= 0) {
            alert('请选择收货商品')
            return
          }
          for (let i in arr) {
            if (!arr[i].arriveNum) {
              alert('请录入收货商品数量')
              return
            }
            if (this.chOrderService.productType === 3 && !arr[i].arrivePackageNum) {
              alert('请录入收货包件数量')
              return
            }
            if (arr[i].arriveNum) {
              let arrivePackageNum = 0
              if (this.chOrderService.productType === 3 || this.chOrderService.productType === 2) {
                arrivePackageNum += arr[i].arrivePackageNum
              } else {
                arrivePackageNum = arr[i].arriveNum * arr[i].packageNum
              }
              productDetailBeans.push({
                packageId: arr[i].packageId,
                productId: arr[i].productId,
                arriveNum: arr[i].arriveNum,
                noArriveNum: arr[i].noArriveNum,
                arrivePackageNum: arrivePackageNum
              })
            }
          }
          this.totalArrive = 0
          this.totalArrivePackage = 0
          if (Array.isArray(productDetailBeans)) {
            for (let i in productDetailBeans) {
              this.totalArrive += productDetailBeans[i].arriveNum
              this.totalArrivePackage += productDetailBeans[i].arrivePackageNum
            }
          }
        }
        if (this.totalNoArrive === this.totalArrive) {
          this.arriveState = 2
        } else {
          this.arriveState = 1
        }
        let url = ''
        let content = ''
        if (this.orderType === 'STORAGEORDERTYPE01') { // 服务订单
          url = '/ms-terminal-order/ch-arrive/arrive-product'
          content = '<p>确定所选商品已经收货？</p><p>收货商品总数：<span style="color:red; font-size: 18px">' + this.totalArrive + '</span>, &nbsp;&nbsp;&nbsp;收货包件总数：<span style="color:red; font-size: 18px">' + this.totalArrivePackage + '</span></p>'
        } else if (this.orderType === 'STORAGEORDERTYPE02') { // 入库订单
          url = '/ms-terminal-order/ch-arrive/arrive-product-record'
          content = '<p>确定所选商品已经收货？</p><p>收货包件总数：<span style="color:red; font-size: 18px">' + this.totalArrive + '</span></p>'
        }
        // 取值
        let data = {
          orderId: this.id,
          cargoOwnerId: this.chOrderService.cargoOwnerId,
          arriveState: this.arriveState,
          chOrderProductBeans: productDetailBeans,
          inputTypeCode: 'CARGOSOURCETYPE01',
          warehouseId: this.chOrderService.warehouseId
        }
        // 提交
        this.$confirm(content, '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          center: true,
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '提交中...'
              this.$ajax.post(url, data).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  this.loading = false
                  setTimeout(() => {
                    this.$confirm('提交成功', '提示', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/ss-oms/orders/arrive-manager/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.loading = false
                  }, 500)
                }
              })
            } else {
              done()
              this.loading = false
            }
          }
        })
      })
    }
  }
}
</script>
